#pragma once

#include "Singleton.h"

#include <boost/asio.hpp>
#include <vector>

class AsioIOServicePool : public Singleton<AsioIOServicePool>
{
    friend Singleton<AsioIOServicePool>;

public:
    using Work = boost::asio::io_context::work;
    using WorkPtr = std::unique_ptr<Work>;

    ~AsioIOServicePool();
    AsioIOServicePool(const AsioIOServicePool&) = delete;
    AsioIOServicePool& operator=(const AsioIOServicePool&) = delete;
    // 使用 round-robin 的方式返回一个 io_service
    boost::asio::io_context& getIOService();

    // 停止服务，回收资源，唤醒挂起的线程
    void stop();

private:
    AsioIOServicePool(std::size_t size = 2/*std::thread::hardware_concurrency()*/);

private:
    std::vector<boost::asio::io_context> m_ioServices;
    // std::vector<std::unique_ptr<boost::asio::io_context::work>> m_works;
    std::vector<WorkPtr> m_works;
    std::vector<std::thread> m_threads;
    std::size_t m_nextIOService; // 下一个io_context的索引（采用轮询的方式）
};
